# -*- coding:utf-8 -*-
from aip import AipOcr
from PIL import Image
import webbrowser
from urllib import quote
import chardet
import urllib
import wda
import os


# """ 你的 APPID AK SK """
APP_ID = '10673375'
API_KEY = '5AVqbtQGZltr49budbrpEWaH'
SECRET_KEY = '24aTSadpC9PAgoPKwveKqSIVajZWlOPM'

c = wda.Client()
s = c.session()

client = AipOcr(APP_ID, API_KEY, SECRET_KEY) 

#截图
def pull_screenshot():
	c.screenshot('screenshot.png')

# 二值化算法
def binarizing(img,threshold):
    pixdata = img.load()
    w, h = img.size
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pixdata[x, y] = 0
            else:
                pixdata[x, y] = 255
    return img


# 去除干扰线算法
def depoint(img):   #input: gray image
    pixdata = img.load()
    w,h = img.size
    for y in range(1,h-1):
        for x in range(1,w-1):
            count = 0
            if pixdata[x,y-1] > 245:
                count = count + 1
            if pixdata[x,y+1] > 245:
                count = count + 1
            if pixdata[x-1,y] > 245:
                count = count + 1
            if pixdata[x+1,y] > 245:
                count = count + 1
            if count > 2:
                pixdata[x,y] = 255
    return img

""" 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

def ocr_img(image):

    # 切割题目和选项位置，左上角坐标和右下角坐标,自行测试分辨率
    question_im = image.crop((50, 250, 700, 500)) # 坚果 pro1
    choices_im = image.crop((50, 500 , 700, 880))
    # question = img.crop((75, 315, 1167, 789)) # iPhone 7P

    # 转化为灰度图
    question_im = question_im.convert('L')
    choices_im = choices_im.convert('L')
    # 把图片变成二值图像。
    question_im=binarizing(question_im,190)
    choices_im = binarizing(choices_im, 190)

    question_im.save('./question.png')
    choices_im.save('./choices.png')

    bd_img_question = get_file_content('./question.png')
    bd_img_choices = get_file_content('./choices.png')

    # """ 如果有可选参数 """
    options = {}
    options["language_type"] = "CHN_ENG"
    options["detect_direction"] = "true"
    options["detect_language"] = "true"
    options["probability"] = "true"

    r = client.basicGeneral(bd_img_question, options)
    c = client.basicGeneral(bd_img_choices, options)

    result = ''

    for i in r['words_result']:
    	result += i['words']
    for i in c['words_result']:
    	result = result + ' ' + i['words']

    result = result[2:]
    print result
    # 转码
    result = result.encode('utf-8')
    result = urllib.quote(result)
    # 打开浏览器
    baidu_search = 'https://baidu.com/s?wd='
    google_search = 'https://www.google.com/search?q='
    webbrowser.open_new_tab(baidu_search + result)

while True:
    # 截图
    pull_screenshot()

    image2 = Image.open("./screenshot.png")

    ocr_img(image2)

    go = raw_input('输入a 回车继续运行,输入 n 回车结束运行: ')
    if go == 'n':
        break

    print('------------------------')


